package org.example.basic_sort;

/**
 * 、插入排序
 * 时间复杂度：O(n^2)
 * 空间复杂度：O(1)
 * 稳定性：稳定
 */
public class Code03_InsertionSort {
    public static void insertionSort(int[] arr) {
        if(arr == null || arr.length < 2) {
            return;
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = i - 1; j >= 0 && arr[j + 1 ] < arr[j ] ; j--) {
                swap(arr,j,j + 1);
            }
        }
    }
    private static void swap(int[] arr, int j, int i) {
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }
    public static void main(String[] args) {
        int[] arr = {1,5,3,6,8};
        insertionSort(arr);
        for (int i : arr) {
            System.out.println(i);
        }
    }
}
